﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Mesuro.Common;
using Mesuro.Equation;

namespace Mesuro.GUI {
	/// <summary>
	/// Interaction logic for EquationEditor.xaml
	/// </summary>
	public partial class EquationEditor : UserControl {
		
		public EquationEditor() {
			InitializeComponent();
		}

		private void lstChannels_MouseUp( object sender, MouseButtonEventArgs e ) {
			Visual v = e.OriginalSource as Visual;
			while (v != null) {
				if (v is ListBoxItem) {
					txtExpression.Text = txtExpression.Text.Trim() + ' ' + ((IChannelRef)lstChannels.SelectedItem).Name;
					return;
				}
				v = VisualTreeHelper.GetParent( v ) as Visual;
			}
		}

		private void lstFunctions_MouseUp( object sender, MouseButtonEventArgs e ) {
			Visual v = e.OriginalSource as Visual;
			while (v != null) {
				if (v is ListBoxItem) {
					txtExpression.Text = txtExpression.Text.Trim() + ' ' + ((EqOperator)lstFunctions.SelectedItem).Symbol;
					return;
				}
				v = VisualTreeHelper.GetParent( v ) as Visual;
			}
		}

		private void txtExpression_TextChanged( object sender, TextChangedEventArgs e ) {
			lblExpression.Visibility = String.IsNullOrWhiteSpace( txtExpression.Text ) ? Visibility.Visible : Visibility.Hidden;
		}

		private void txtChannelName_TextChanged( object sender, TextChangedEventArgs e ) {
			lblChannelName.Visibility = String.IsNullOrWhiteSpace( txtChannelName.Text ) ? Visibility.Visible : Visibility.Hidden;
		}

		private void chkAllChannels_Checked( object sender, RoutedEventArgs e ) {
			lstChannels.SetBinding( ListBox.ItemsSourceProperty, new Binding( "DataSet.AllChannels" ) { Source = this } );
		}

		private void chkAllChannels_Unchecked( object sender, RoutedEventArgs e ) {
			lstChannels.SetBinding( ListBox.ItemsSourceProperty, new Binding( "DataSet.PreferredChannels" ) { Source = this } );
		}

		private void btnOkay_Click( object sender, RoutedEventArgs e ) {
			ISeries series;
			VirtualChannelCallback vcc = EqParser.Parse( txtExpression.Text,out series );
			DataSet.RegisterVirtualChannel( series, txtChannelName.Text, vcc );
		}



	}
}
